package com.ecloud.gardenscenter.common.standard;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Squbi
 */
public interface EnableToEntities<T> {

    /**
     * 如果名称一致 将当前类属性映射到指定实体类
     *
     * @param t T类型的实例
     * @return T 类型的实例
     * @throws IllegalAccessException 当反射注入数据异常时抛出错误
     * @author Squbi
     * @date 2021/7/28 15:06
     */
    default T toEntities(T t) throws IllegalAccessException {
        Class<?> clazz = this.getClass();
        Map<String, Object> thisFields = new HashMap<>();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            thisFields.put(field.getName(), field.get(this));
        }
        for (Field field : t.getClass().getDeclaredFields()) {
            Object o = thisFields.get(field.getName());
            if (o != null) {
                field.setAccessible(true);
                field.set(t, o);
            }
        }
        return t;
    }
}
